package com.putao.album.tag;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.photodetail.ActivityPhotoDetail;
import com.putao.album.tag.adapter.TagAlbumPhotoAdapter;
import com.putao.album.tag.bean.TagAlbumPhotoItem;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.widget.pullrefresh.PullToRefreshBase;
import com.putao.album.widget.pullrefresh.PullToRefreshGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by jidongdong on 15/4/28.
 * <p/>
 * 单个标签相册的照片列表
 */
public class ActivityTagAlbumPhotoList extends BaseActivity {
    private Button right_btn;
    private TextView title_tv;
    private PullToRefreshGridView gv_photolist;
    private ArrayList<TagAlbumPhotoItem> mDataList = new ArrayList<TagAlbumPhotoItem>();
    private TagAlbumPhotoAdapter mTagAlbumPhotoAdapter;
    private String mTagName;
    private String nextPage = "1";
    private boolean mIsLastPage = false;
    private boolean mIsRefreshing = false;
    private RelativeLayout list_empty_view;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_tag_album_photo_list;
    }

    @Override
    public void doInitSubViews(View view) {
        setPageTitle();
        queryViewById(R.id.back_btn, true);
        gv_photolist = queryViewById(R.id.gv_photolist);
        right_btn = queryViewById(R.id.right_btn, true);
        right_btn.setBackgroundResource(R.drawable.album_button_edit);
        list_empty_view = queryViewById(R.id.list_empty_view);
        list_empty_view.setVisibility(View.GONE);
        EventBus.getDefault().register(this);
    }

    @Override
    public void doInitData() {
        mTagAlbumPhotoAdapter = new TagAlbumPhotoAdapter(mContext, mDataList);
        gv_photolist.setAdapter(mTagAlbumPhotoAdapter);
        mTagAlbumPhotoAdapter.notifyDataSetChanged();
        gv_photolist.setLongClickable(false);
        gv_photolist.getRefreshableView().setOnItemClickListener(mOnItemClickListener);
        gv_photolist.getRefreshableView().setNumColumns(2);
        gv_photolist.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                refreshData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {

            }
        });
        gv_photolist.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                updateData();
            }
        });
        updateData();
    }

    public void onEvent(BasePostEvent event) {
        switch (event.eventCode) {
            case PuTaoConstants.EVENTBUS_BATCH_REMOVE_TAG_PHOTO:
            case PuTaoConstants.EVENTBUS_BATCH_ADD_TAG_PHOTO:
                refreshData();
                break;
        }
    }

    void refreshData() {
        nextPage = "1";
        mIsLastPage = false;
        updateData();
    }


    protected void updateData() {

        if (mIsLastPage || mIsRefreshing) {
            gv_photolist.onRefreshComplete();
            return;
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("page", nextPage);
        params.put("tag", mTagName);
        params.put("baby_id", CommonUtils.getBabyId());
        Loger.d("baby_id:" + CommonUtils.getBabyId());
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_TAG_PHOTO_LIST, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        doAnalyzeDataList(HttpRequestUtil.getResponseData(response));
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
        mIsRefreshing = true;

    }

    /**
     * 解析返回的标签相册列表数据
     *
     * @param data
     */
    void doAnalyzeDataList(JSONObject data) {
        JSONArray list = data.optJSONArray("photoList");
        if (list != null) {
            if (nextPage.equals("1")) {
                mDataList.clear();
            }
            for (int i = 0; i < list.length(); i++) {
                JSONObject o = null;
                try {
                    o = list.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (o != null) {
                    String image_id = o.optString("photo_id");
                    String url = o.optString("photo");
                    String is_praise = o.optString("is_praise");
                    TagAlbumPhotoItem item = new TagAlbumPhotoItem();
                    item.image_id = image_id;
                    item.image_url = url;
                    item.is_praise = is_praise.equals("1");
                    mDataList.add(item);
                }
            }

            if (mDataList.size() > 0) {
                list_empty_view.setVisibility(View.GONE);
            } else {
                list_empty_view.setVisibility(View.VISIBLE);
            }

            mTagAlbumPhotoAdapter.notifyDataSetChanged();
        }
        nextPage = data.optString("nextPage");
        gv_photolist.onRefreshComplete();
        mIsRefreshing = false;
        if (nextPage.equals("-1")) {
            mIsLastPage = true;
        }
    }

    void setPageTitle() {
        title_tv = queryViewById(R.id.title_tv);
        if (getIntent() != null) {
            Bundle bundle = getIntent().getExtras();
            if (bundle != null)
                mTagName = bundle.getString("tag_name", "");
        }
        title_tv.setText(mTagName);
    }


    /**
     * 长按
     */
    AdapterView.OnItemLongClickListener mOnItemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Bundle bundle = new Bundle();
            //TODO:传入标签的名称
            bundle.putString("tag_name", mTagName);
            ActivityHelper.startActivity(mActivity, ActivityTagAlbumPhotoRemove.class, bundle);
            return false;
        }
    };

    /**
     * 单击
     */
    AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ArrayList<String> ids = new ArrayList<String>();
            for (int i = 0; i < mDataList.size(); i++) {
                ids.add(mDataList.get(i).image_id);
            }
            Bundle bundle = new Bundle();
            bundle.putStringArrayList("ids", ids);
            bundle.putInt("position", position);
            ActivityHelper.startActivity(mActivity, ActivityPhotoDetail.class, bundle);
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.right_btn:
                Bundle bundle = new Bundle();
                //TODO:传入标签的名称
                bundle.putString("tag_name", mTagName);
                ActivityHelper.startActivity(mActivity, ActivityTagAlbumPhotoRemove.class, bundle);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
